#include "e2d/core/trans/AnimationClip.h"
#include "e2d/core/trans/TransformNode.h"
#include "e2d/core/Entity.h"

void e2d::AnimationClip::OnLoad()
{
	m_AnimationNode.LoadAnim();
	InitAnimNode(m_Entity);
};

void e2d::AnimationClip::OnStart()
{
}

void e2d::AnimationClip::OnUpdate()
{

}

void e2d::AnimationClip::OnMove()
{
	auto& m_AnimationMap = m_AnimationNode.m_AnimationMap;
	auto& m_Animation = m_AnimationMap.m_Value;

	if (!m_Animation)
	{
		return;
	}
	auto& m_AnimAxis = m_AnimationNode.m_AnimAxis;


	auto& transformNode = m_Entity->Get<e2d::TransformNode>();
	auto& world = transformNode.m_World;

	auto input = Input();
	auto timer = Timer();

	bool isKeyPressingUp = input->m_Keyboard.IsPressing(KeyCode::UP);
	bool isKeyPressingDown = input->m_Keyboard.IsPressing(KeyCode::DOWN);

	float speed = 40.0f;
	float animSpeed = .25f;

	if (isKeyPressingUp)
	{
		world.m_Position += timer->DeltaTime() * speed * world.GetForward();
		m_AnimAxis += Timer()->DeltaTime() / m_Animation->m_TotalTime *animSpeed;
		transformNode.ResetLocalFromWorld();
	}

	if(isKeyPressingDown)
	{
		world.m_Position -= timer->DeltaTime() * speed * world.GetForward();
		m_AnimAxis-= Timer()->DeltaTime() / m_Animation->m_TotalTime * animSpeed;
		transformNode.ResetLocalFromWorld();
	}
}

void e2d::AnimationClip::OnUpdateRuntime()
{
	if (!m_AnimationNode.m_AnimationMap.m_Value)
	{
		return;
	}

	auto& m_AnimAxis = m_AnimationNode.m_AnimAxis;
	auto& m_Animation = m_AnimationNode.m_AnimationMap;

	m_AnimationNode.Tick(Timer()->DeltaTime());

	if (m_AnimAxis > 0.99f)
	{
		m_AnimAxis = 0.01f;
	}
	if (m_AnimAxis < 0.01f)
	{
		m_AnimAxis = 0.99f;
	}

	m_AnimationNode.UpdateBoneData();
}


void e2d::AnimationClip::OnDestroy()
{
}

float e2d::AnimationClip::AnimAxis()
{
	return m_AnimationNode.m_AnimAxis;
}

bool e2d::AnimationClip::InitAnimNode(e2d::Entity* entity)
{
	auto anim = m_AnimationNode.GetAnimation();

	if (!anim)
	{
		return false;
	}
	if (!entity)
	{
		return false;
	}
	
	return ProcessAnimNode(entity, anim.get());

}

bool e2d::AnimationClip::ProcessAnimNode(e2d::Entity* entity, e2d::Animation* anim)
{

	bool hasNode = anim->HasChannel(entity->m_Name);

	if (hasNode)
	{
		ztclog::info("has node %s", entity->m_Name.c_str());
	}
	else
	{
		ztclog::info("dot has node %s", entity->m_Name.c_str());
	}

	if(anim->SetAnimNode(entity->m_Name, entity))
	{
		ztclog::info("set node %s", entity->m_Name.c_str());
	}

	
	for (auto child : entity->m_Children)
	{
		ProcessAnimNode(child.get(), anim);
	}
	return true;
}

